package cn.rayfoo.common.exception;

import cn.rayfoo.common.response.HttpStatus;
import cn.rayfoo.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author rayfoo@qq.com
 * @version 1.0
 * @date 2020/8/5 14:55
 * @description 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class AdviceExceptionResolver {


    /**
     * 处理自定义的异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(MyException.class)
    public Result resolveMyException(MyException exception) {
        //打印完整的异常信息
        exception.printStackTrace();
        //创建result
        Result result = Result.builder()
                .code(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .msg(exception.getMsg())
                .data(exception.getMsg())
                .build();
        //保存自定义异常日志
        log.error(exception.getMsg());
        return result;
    }

    /**
     * 处理所有RuntimeException异常
     */
    @ExceptionHandler({RuntimeException.class})
    public Result allException(RuntimeException exception) {
        exception.printStackTrace();
        //封装返回结果
        Result result = Result.builder()
                .code(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .msg(exception.getMessage())
                .build();
        //记录日志
        log.error(exception.getMessage());
        exception.printStackTrace();
        return result;
    }

    /**
     * 处理所有Exception异常
     */
    @ExceptionHandler({Exception.class})
    public Result allException(Exception exception) {
        exception.printStackTrace();
        //封装返回结果
        Result result = Result.builder()
                .code(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .msg(exception.getMessage())
                .build();
        //记录日志
        log.error(exception.getMessage());
        return result;
    }


}
